<template>
  <div class="get-pokemon-page">
    <!-- Header -->
    <div class="header">
      <button class="back-button" @click="goHome">
        <span class="back-icon">←</span>
      </button>
      <h1 class="header-title">获取宝可梦</h1>
    </div>

    <!-- Content -->
    <div class="content">
      <div v-if="!isSearching && !pokemon" class="pokeball-container">
        <img class="normal-pokemon-ball click-style" @click="startSearch" src="/public/pokeball/pokeball.svg"/>
        <span>尝试获得一只宝可梦</span>
      </div>

      <div v-if="isSearching" class="searching-container">
        <p class="searching-text">正在搜索宝可梦...</p>
        <div class="progress-bar">
          <div class="progress-fill" :style="{ width: `${progress}%` }"></div>
        </div>
      </div>

      <div v-if="pokemon && !showBattle" class="pokemon-container">
        <img
            :src="`https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${pokemon.id}.png`"
            :alt="pokemon.name"
            class="pokemon-image"
        />
        <h2 class="pokemon-name">{{ pokemon.name }}</h2>
        <p class="pokemon-level">Lv. {{ pokemon.level }}</p>
        <div class="type-badges">
          <span
              v-for="(type, index) in pokemon.type.split('/')"
              :key="index"
              class="type-badge"
              :style="{ backgroundColor: getTypeColor(type) }"
          >
            {{ type }}
          </span>
        </div>
        <div class="action-buttons">
          <button class="battle-button" @click="startBattle">战斗</button>
          <button class="search-button" @click="startSearch">再次搜索</button>
        </div>
      </div>

      <Battle
          v-if="showBattle && playerPokemonList.length > 0"
          :player-pokemon="playerPokemonList"
          :opponent-pokemon="[pokemon]"
          @battle-end="handleBattleEnd"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, inject, onMounted, computed, nextTick } from 'vue';
import Battle from './Battle.vue';
import pokemon_enService from '@/api/services/pokemon_enService';
import movesService from '@/api/services/movesService';
import { typeMap, typeColorMap } from '@/api/constants';

// Helper function to calculate Pokémon stats
const calculateStat = (base, level, iv = 15, ev = 0, isHp = false) => {
  const basePart = Math.floor(((2 * base + iv + Math.floor(ev / 4)) * level) / 100);
  return isHp ? basePart + level + 10 : basePart + 5;
};

const navigate = inject('navigate');
const myPokemon = inject('myPokemon');
const boxPokemon = inject('boxPokemon');

// Load from localStorage on mount
onMounted(() => {
  const storedMyPokemon = localStorage.getItem('myPokemon');
  const storedBoxPokemon = localStorage.getItem('boxPokemon');
  if (storedMyPokemon) myPokemon.value = JSON.parse(storedMyPokemon);
  if (storedBoxPokemon) boxPokemon.value = JSON.parse(storedBoxPokemon);
  console.log('myPokemon.value.length onMounted:', myPokemon?.value?.length);
});

const isSearching = ref(false);
const progress = ref(0);
const pokemon = ref(null);
const showBattle = ref(false);

const playerPokemonList = computed(() => {
  if (myPokemon && myPokemon.value && Array.isArray(myPokemon.value) && myPokemon.value.length > 0) {
    return [myPokemon.value[0]];
  }
  return [];
});

const getTypeColor = (type) => {
  return typeColorMap[type] || '#9e9e9e';
};

const startSearch = async () => {
  isSearching.value = true;
  progress.value = 0;
  pokemon.value = null;
  showBattle.value = false;

  const interval = setInterval(() => {
    progress.value += 1;
    if (progress.value >= 100) {
      clearInterval(interval);
    }
  }, 30);

  setTimeout(async () => {
    try {
      const randomId = Math.floor(Math.random() * 898) + 1;
      const pokemonResponse = await pokemon_enService.getPokemonById(randomId);
      const types = pokemonResponse.types
          .map(t => typeMap[t.type.name.toLowerCase()] || t.type.name)
          .join('/');
      const stats = pokemonResponse.stats.reduce((acc, stat) => {
        acc[stat.stat.name] = stat.base_stat;
        return acc;
      }, {});
      const level = Math.floor(Math.random() * 16) + 5;

      const moveIds = pokemonResponse.moves
          .slice(0, 4)
          .map(move => move.move.url.split('/').slice(-2, -1)[0]);

      const moves = await Promise.all(
          moveIds.map(async (moveId) => {
            try {
              const moveResponse = await movesService.getMoveById(moveId);
              return {
                name: moveResponse.name_zh,
                type: typeMap[moveResponse.type.toLowerCase()] || moveResponse.type,
                pp: 25
              };
            } catch (error) {
              return { name: '撞击', type: '一般', pp: 35 };
            }
          })
      );

      pokemon.value = {
        id: pokemonResponse.id,
        name: pokemonResponse.name,
        type: types,
        level,
        hp: calculateStat(stats.hp || 50, level, 15, 0, true),
        maxHp: calculateStat(stats.hp || 50, level, 15, 0, true),
        attack: calculateStat(stats.attack || 50, level),
        defense: calculateStat(stats.defense || 50, level),
        specialAttack: calculateStat(stats['special-attack'] || 50, level),
        specialDefense: calculateStat(stats['special-defense'] || 50, level),
        speed: calculateStat(stats.speed || 50, level),
        moves: moves.length > 0 ? moves : [{ name: '撞击', type: '一般', pp: 35 }]
      };
      isSearching.value = false;
    } catch (error) {
      console.error('Error fetching Pokémon:', error);
      isSearching.value = false;
      pokemon.value = null;
    }
  }, 3000);
};

const startBattle = () => {
  if (!myPokemon || !myPokemon.value || !Array.isArray(myPokemon.value) || myPokemon.value.length === 0) {
    alert('你的队伍中没有宝可梦，无法开始战斗！请先回去获取一些宝可梦。');
    return;
  }
  showBattle.value = true;
};

const handleBattleEnd = (result) => {
  showBattle.value = false;
  if (result === 'caught') {
    const newPokemon = { ...pokemon.value, hp: pokemon.value.maxHp };
    if (myPokemon.value.length < 3) {
      myPokemon.value.push(newPokemon);
      console.log(`${newPokemon.name} 已加入你的队伍！`);
    } else {
      if (!boxPokemon.value) boxPokemon.value = [];
      boxPokemon.value.push(newPokemon);
      console.log(`${newPokemon.name} 已加入你的宝可梦箱！`);
    }
    localStorage.setItem('myPokemon', JSON.stringify(myPokemon.value));
    localStorage.setItem('boxPokemon', JSON.stringify(boxPokemon.value));
    pokemon.value = null;
  }
};

const goHome = () => {
  navigate('home');
};
</script>

<style scoped>
.get-pokemon-page {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.header {
  background-color: #333;
  color: white;
  padding: 16px;
  display: flex;
  align-items: center;
}

.back-button {
  background: none;
  color: white;
  margin-right: 16px;
  padding: 8px;
}

.back-icon {
  font-size: 24px;
}

.header-title {
  font-size: 20px;
  font-weight: bold;
}

.content {
  flex: 1;
  padding: 16px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.pokeball-container {
  display: flex;
  text-align: center;
  flex-direction: column;
  align-items: center;
}

.pokeball-button {
  background: radial-gradient(circle, #fff 30%, #e0e0e0 50%, #ff0000 50%, #ff0000 60%, #fff 60%);
  border: 4px solid #000;
  border-radius: 50%;
  width: 100px;
  height: 100px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  color: #000;
  position: relative;
  overflow: hidden;
}

.pokeball-button::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 0;
  right: 0;
  height: 8px;
  background: #000;
}

.pokeball-button:hover {
  transform: scale(1.1);
}

.searching-container {
  text-align: center;
}

.searching-text {
  font-size: 18px;
  color: #333;
  margin-bottom: 16px;
}

.progress-bar {
  width: 200px;
  height: 10px;
  background-color: #eee;
  border-radius: 5px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background-color: #e74c3c;
  transition: width 0.03s linear;
}

.pokemon-container {
  text-align: center;
}

.pokemon-image {
  width: 150px;
  height: 150px;
}

.pokemon-name {
  font-size: 24px;
  font-weight: bold;
  margin: 16px 0 8px;
}

.pokemon-level {
  font-size: 16px;
  color: #666;
  margin-bottom: 8px;
}

.type-badges {
  display: flex;
  gap: 8px;
  justify-content: center;
  margin-bottom: 16px;
}

.type-badge {
  font-size: 12px;
  padding: 4px 12px;
  border-radius: 12px;
  color: white;
}

.action-buttons {
  display: flex;
  gap: 16px;
}

.battle-button {
  background-color: #e74c3c;
  color: white;
  padding: 12px 24px;
}

.battle-button:hover {
  background-color: #c0392b;
}

.search-button {
  background-color: #3498db;
  color: white;
  padding: 12px 24px;
}

.search-button:hover {
  background-color: #2980b9;
}

.normal-pokemon-ball {
  margin-bottom: 20px;
  width: 250px;
  height: 250px;
  border-radius: 50%;
  background: radial-gradient(50% 50% at 50% 50%, #FFFFFF 15%, transparent 15%, transparent 90%), radial-gradient(50% 50% at 50% 50%, transparent 15%, #000000 15%, #000000 25%, transparent 25%, transparent 70%), linear-gradient(to top, transparent 47.5%, #000000 47.5%, #000000 52.5%, transparent 52.5%), linear-gradient(to top, #FFFFFF 50%, var(--color-red) 50%);
  transition: 200ms;
  overflow: hidden;
}

.click-style {
  cursor: pointer;
  user-select: none;
}
</style>